#include <time/time.h>
#include <hw/rtc.h>

// January 1st, 1970, 00:00:00
struct tm EPOCH = { 0, 0, 0, 1, 1, 1970, 0, 0, 0 };

// days per month in a non-leap year
int DAYS_IN_MONTH[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

time_t current_time = 0;
uint32 current_millis = 0;

void time_update() {
    if (current_time == 0) {
        current_time = get_rtc_time();
    } else {
        current_millis ++;
        if (current_millis % 1000 == 0) {
            current_time ++;
            current_millis = 0;
        }
    }
}

unsigned char is_leap(int year) {
    if (year % 400 == 0) {
        return 1;
    }
    if (year % 100 == 0) {
        return 0;
    }
    return (year % 4 == 0);
}

// FIXME:Currently this function doesn't deal with dates before 1970
time_t mktime(struct tm *tp) {
    time_t t = tp->tm_sec;
    t += tp->tm_min * 60;
    t += tp->tm_hour * 3600;
    t += (tp->tm_mday - 1) * 86400;
    int y = 0;
    for (y = EPOCH.tm_year; y < tp->tm_year; y++) {
        t += 86400 * 365;
        if (is_leap(y)) {
            t += 86400;
        }
    }

    int m = 0;
    for (m = EPOCH.tm_mon; m < tp->tm_mon; m++) {
        t += 86400 * DAYS_IN_MONTH[m];
        if (m == 2 && is_leap(tp->tm_year)) {
            t += 86400;
        }
    }

    return t;
}

time_t time() {
    if (current_time == 0) {
        time_update();
    }
    return current_time;
}

